package com.pioneer.web.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pioneer.common.config.CommonConfig;
import com.pioneer.common.exception.CustomException;
import com.pioneer.common.utils.SecurityUtils;
import com.pioneer.web.system.domain.SysDatabase;
import com.pioneer.web.system.mapper.SysDatabaseMapper;
import com.pioneer.web.system.service.ISysDatabaseService;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库备份管理
 *
 * @Author wf
 * @Date 2023-03-28 13:32:15
 **/
@Service
public class SysDatabaseServiceImpl extends ServiceImpl<SysDatabaseMapper, SysDatabase> implements ISysDatabaseService {

    @Override
    public String backupDatabase() {
        long timeMillis = System.currentTimeMillis();
        StringBuffer stringBuffer = new StringBuffer();
        Map<String, String> map = delUrl(CommonConfig.getUrl());
        StringBuffer append = stringBuffer.append(timeMillis).append(map.get("database")).append(".sql");
        String str = append.toString();
        if (!exportDatabaseTool(map.get("ip"), map.get("port"), CommonConfig.getUsername(), CommonConfig.getPassword(), CommonConfig.getDownloadPath(), str, map.get("database"))) {
            throw new CustomException("数据库备份失败");
        }
        SysDatabase sysDatabase = new SysDatabase();
        sysDatabase.setName(map.get("database"));
        sysDatabase.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        sysDatabase.setUrl(str);
        add(sysDatabase);
        return str;

    }

    @Override
    public int add(SysDatabase sysDatabase) {
        return baseMapper.insert(sysDatabase);
    }

    /**
     * Java代码实现MySQL数据库导出
     *
     * @param hostIP       MySQL数据库所在服务器地址IP
     * @param port         端口
     * @param userName     进入数据库所需要的用户名
     * @param password     进入数据库所需要的密码
     * @param savePath     数据库导出文件保存路径
     * @param fileName     数据库导出文件文件名
     * @param databaseName 要导出的数据库名
     * @return 返回true表示导出成功，否则返回false。
     * @author GaoHuanjie
     */
    private boolean exportDatabaseTool(String hostIP, String port, String userName, String password, String savePath, String fileName, String databaseName) {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("cmd /c mysqldump").append(" -h").append(hostIP);
        stringBuilder.append(" -P").append(port);
        stringBuilder.append(" -u").append(userName).append(" -p").append(password);
        stringBuilder.append(" --databases ").append(databaseName).append(">").append(savePath + fileName);

        try {
            System.out.println(stringBuilder);
            Process process = Runtime.getRuntime().exec(stringBuilder.toString());
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Map<String, String> delUrl(String url) {
        String s = StrUtil.subSuf(url, 13);
        String ip = StrUtil.subBefore(s, ":", false);
        s = StrUtil.subAfter(s, ":", false);
        String port = StrUtil.subBefore(s, "/", false);
        String database = StrUtil.subAfter(s, "/", false);
        if (database.contains("?")) {
            database = StrUtil.subBefore(database, "?", false);
        }
        Map<String, String> map = new HashMap<>();
        map.put("ip", ip);
        map.put("port", port);
        map.put("database", database);
        return map;
    }

}
